package com.yunban.project.api.text_check.utils;

import com.alibaba.fastjson.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicSessionCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.lke.v20231130.LkeClient;
import com.tencentcloudapi.lke.v20231130.models.Credentials;
import com.tencentcloudapi.lke.v20231130.models.DescribeStorageCredentialRequest;
import com.tencentcloudapi.lke.v20231130.models.DescribeStorageCredentialResponse;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

/**
 * @author: lijiajun
 * @date: 2025-02-26
 * @version: 1.0
 */
@Slf4j
@Component
public class DeepSeekApplication {

    private static final String EndPoint = "lke.tencentcloudapi.com";
    private static final String SecretID = "AKIDRnCTZS7apqkR8brtiKGSRKApTHuNf0FO ";
    private static final String SecretKey = "DE2mMjvufDXdWBcqrYBcrthKkwvhIjxy";
    private static final String BotBizID = "1894937015376150528";
    private static final String Region = "ap-guangzhou";
    private static final String TypeKey = "realtime";
    private static final String DocParseUrl = "https://wss.lke.cloud.tencent.com/v1/qbot/chat/docParse";
    private static final String BotAppKey = "ytRAUdZs";

    /**
     * DescribeStorageCredential
     */
    public DescribeStorageCredentialResponse getTemSecretInfo(String fileType) {
        Credential cred = new Credential(SecretID, SecretKey);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(EndPoint);
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        LkeClient client = new LkeClient(cred, Region, clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        DescribeStorageCredentialRequest req = new DescribeStorageCredentialRequest();
        req.setFileType(fileType);
        req.setBotBizId(BotBizID);
        req.setIsPublic(false);
        req.setTypeKey(TypeKey);
        // 返回的resp是一个DescribeStorageCredentialResponse的实例，与请求对象对应
        try {
            return client.DescribeStorageCredential(req);
        } catch (TencentCloudSDKException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取 Cos Client
     *
     * @param describeStorageCredentialResponse Storage 凭证响应
     * @return COSClient
     */
    COSClient getCosClient(DescribeStorageCredentialResponse describeStorageCredentialResponse) {
        Credentials credentials = describeStorageCredentialResponse.getCredentials();
        String tmpSecretId = credentials.getTmpSecretId();
        String tmpSecretKey = credentials.getTmpSecretKey();
        String tmpToken = credentials.getToken();
        String regionInfo = describeStorageCredentialResponse.getRegion();
        System.out.println("【DeepSeekApplication.getCosClient】tmpSecretId：" + tmpSecretId);
        System.out.println("【DeepSeekApplication.getCosClient】tmpSecretKey：" + tmpSecretKey);
        System.out.println("【DeepSeekApplication.getCosClient】tmpToken：" + tmpToken);
        // ObjectMetadata metadata = new ObjectMetadata();
        BasicSessionCredentials cosCred = new BasicSessionCredentials(tmpSecretId, tmpSecretKey, tmpToken);
        // region
        System.out.println("【DeepSeekApplication.getCosClient】regionInfo：" + regionInfo);
        com.qcloud.cos.region.Region region = new Region(regionInfo);
        ClientConfig clientConfig = new ClientConfig(region);
        return new COSClient(cosCred, clientConfig);
    }

    /**
     * 上传文件
     *
     * @param cosClient                         cosClient
     * @param describeStorageCredentialResponse Storage 凭证响应
     * @param file                              文件
     * @return PutObjectResult
     */
    public PutObjectResult upload(COSClient cosClient, DescribeStorageCredentialResponse describeStorageCredentialResponse, MultipartFile file) {
        String bucket = describeStorageCredentialResponse.getBucket();
        String uploadPath = describeStorageCredentialResponse.getUploadPath();
        File tempFile = null;
        try {
            // 将 MultipartFile 转换为 InputStream
            InputStream inputStream = file.getInputStream();
            // 创建 PutObjectRequest 对象
            // 将 MultipartFile 转换为临时文件
            tempFile = File.createTempFile("upload", null);
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(file.getBytes());
            }
            tempFile = new File("E://Desktop/冠绝天下，探寻中国近代童帽银饰的璀璨之旅！.docx");
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, uploadPath, tempFile);
//            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, uploadPath, new File(filePath));
            System.out.println(JSON.toJSONString(putObjectRequest));
            return cosClient.putObject(putObjectRequest);
        } catch (IOException e) {
            log.error("【DeepSeekApplication.upload】文件上传-发生异常：", e);
            log.error("【DeepSeekApplication.upload】文件上传-发生异常：{}", e.getMessage());
            throw new BusinessException("文件上传失败:" + e.getMessage());
        } finally {
            // 删除临时文件
            if (!ObjectUtils.isEmpty(tempFile)) {
                boolean isDelete = tempFile.delete();
                log.info("【DeepSeekApplication.upload】文件上传-删除临时文件：{}", isDelete);
            }
        }

    }

    /**
     * 获取文件后缀
     *
     * @param file 文件
     * @return FileInfo fileInfo
     */
    public FileInfo getFileExt(MultipartFile file) {
        // 检查文件是否为空
        if (ObjectUtils.isEmpty(file) || file.isEmpty()) {
            throw new BusinessException("文件信息错误");
        }
        // 获取文件后缀名
        String fileName = file.getOriginalFilename();
        // 获取文件大小
        String fileSize = String.valueOf(file.getSize());
        if (StringUtils.hasText(fileName)) {
            int dotIndex = fileName.lastIndexOf('.');
            if (dotIndex != -1 && dotIndex < fileName.length() - 1) {
                return new FileInfo(fileName, fileName.substring(dotIndex + 1), fileSize);
            }
        }
        // 只能接收 doc / docx
        throw new BusinessException("文件信息错误");
    }

    // 实时文档解析
    public String docParse(DescribeStorageCredentialResponse describeStorageCredentialResponse, PutObjectResult putObjectResult, FileInfo fileInfo) {
        // 3.调用SaveDoc,将相关元数据存储到知识引擎
        String bucket = describeStorageCredentialResponse.getBucket();
        String fileExt = fileInfo.getExt();
        String fileName = fileInfo.getFileName();
        String fileSize = fileInfo.getFileSize();
        String uploadPath = describeStorageCredentialResponse.getUploadPath();
        String eTag = putObjectResult.getETag();
        String cosHash = putObjectResult.getCrc64Ecma();
        try {
            HttpClient client1 = HttpClient.newHttpClient();
            // 构建请求体的JSON字符串
            String requestBody = "{\n" +
                    "  \"session_id\": \"" + UUID.randomUUID() + "\",\n" +
                    "  \"request_id\": \"" + UUID.randomUUID() + "\",\n" +
                    "  \"cos_bucket\": \"" + bucket + "\",\n" +
                    "  \"file_type\": \"" + fileExt + "\",\n" +
                    "  \"file_name\": \"" + fileName + "\",\n" +
                    "  \"cos_url\": \"" + uploadPath + "\",\n" +
                    "  \"e_tag\": \"" + eTag + "\",\n" +
                    "  \"cos_hash\": \"" + cosHash + "\",\n" +
                    "  \"size\": \"" + fileSize + "\",\n" +
                    "  \"bot_app_key\": \"" + BotAppKey + "\"\n" +
                    "}";
            // 创建HttpRequest对象
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(DocParseUrl))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并获取响应
            HttpResponse<String> response = client1.send(request, HttpResponse.BodyHandlers.ofString());
            return response.body();
        } catch (Exception e) {
            log.error("【DeepSeekApplication.docParse】文件解析-发生异常：", e);
            log.error("【DeepSeekApplication.docParse】文件解析-发生异常：{}", e.getMessage());
            throw new BusinessException("文件解析失败:" + e.getMessage());
        }
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class FileInfo {
        private String fileName;
        private String ext;
        private String fileSize;
    }

    public static MultipartFile convert(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        return new MockMultipartFile(
                file.getName(), // 文件名
                file.getName(), // 原始文件名
                null, // 内容类型，可以设置为 null 或者根据文件类型设置
                inputStream // 输入流
        );
    }

    public static void main(String[] args) {
        DeepSeekApplication deepSeekApplication = new DeepSeekApplication();
        File file = new File("E://Desktop/冠绝天下，探寻中国近代童帽银饰的璀璨之旅！.docx");
        try {
            MultipartFile multipartFile = convert(file);
            FileInfo fileInfo = deepSeekApplication.getFileExt(multipartFile);
            System.out.println(fileInfo);
            DescribeStorageCredentialResponse describeStorageCredentialResponse = deepSeekApplication.getTemSecretInfo(fileInfo.getExt());
            COSClient cosClient = deepSeekApplication.getCosClient(describeStorageCredentialResponse);
            if (ObjectUtils.isEmpty(cosClient)) {
                throw new BusinessException("cosClient获取失败");
            }
            PutObjectResult putObjectResult = deepSeekApplication.upload(cosClient, describeStorageCredentialResponse, multipartFile);
//            System.out.println(JSON.toJSONString(putObjectResult));
            String docParse = deepSeekApplication.docParse(describeStorageCredentialResponse, putObjectResult, fileInfo);
            System.out.println(docParse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
